<template>
  <div class="department-container">
    <el-tabs value="first">
      <el-tab-pane label="组织架构" name="first" />
      <el-card>
        <!-- 用一个行列布局 -->
        <el-row type="flex" justify="space-between" align="middle" style="height: 40px;border-bottom: 1px solid #cfcfcf;">
          <el-col :span="20">
            <span>江苏传智播客教育科技股份有限公司</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex" justify="end">
              <el-col>负责人</el-col>
              <el-col>
                <!-- 下拉菜单 -->
                <el-dropdown>
                  <span>操作<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="openAddDialog('')">添加部门</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <!-- 树形组件 -->
        <!-- 凡是需要适配具体数据类型的属性必须加上冒号-->
        <!--
          tree组件默认识别的字段
          label和chilren 如果后端发回来的数据不叫这个 需要自定义识别字段

          如何给组件传递属性？
           1. 不加冒号  name="this is name" 永远是字符串类型 isTrue="false" count="123"
           2. 加冒号
              使用当前组件实例身上的属性  data/computed 产出的数据
              直接识别类型的数据 boolean number 数组 对象
               <AComponent :list="[1,2,3]" :is-true="true"/>
         -->
        <el-tree
          :data="treeList"
          :props="defaultProps"
          :default-expand-all="true"
        >
          <!-- 作用域插槽 data拿到的是每一个子节点的对象 -->
          <!-- data是固定写法，代表组件抛出数据 -->
          <!--
            {data} data是固定的吗？固定的 解构赋值的写法
            #default="scope"  scope不是固定的 类似于函数的形参
            用组件都是已经写好了一半 容许我们传入参数 也给我们抛出了现成的数据

            数据调试
             1. 差值渲染
             2. 设计一个小点击事件 当成参数传入 打印
          -->
          <template #default="{data}">
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
              style="height:40px; width:100%;"
            >
              <el-col :span="20">
                <span>{{ data.name }}</span>
              </el-col>
              <el-col :span="4">
                <el-row type="flex" justify="end">
                  <el-col class="manager">{{ data.manager }}</el-col>
                  <el-col>
                    <!-- 下拉菜单 -->
                    <el-dropdown>
                      <span>操作<i class="el-icon-arrow-down el-icon--right" />
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="openAddDialog(data.id)">添加子部门</el-dropdown-item>
                        <el-dropdown-item @click.native="editDepart(data.id)">编辑部门</el-dropdown-item>
                        <el-dropdown-item @click.native="delDepart(data.id)">删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-card>

    </el-tabs>
    <!-- 新增部门dialog -->
    <el-dialog
      :title="dialogTitle"
      :visible="addVisible"
      width="500px"
      @close="closeAddDialog"
    >
      <el-form ref="addform" :model="departInfo" :rules="rules" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departInfo.name" placeholder="1~50个字符" style="width:80%" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="departInfo.code" placeholder="1~50个字符" style="width:80%" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="departInfo.manager" placeholder="请选择部门负责人" style="width:80%">
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="departInfo.introduce" placeholder="1~300个字符" style="width:80%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="clickSubmit">确 定</el-button>
        <el-button size="small" @click="closeAddDialog">取 消</el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>
/**
 1. 获取列表渲染
 思路: 1.定义响应式数据 -> 2.调用接口获取数据 -> 3. 把数据复制给响应式的属性
 拓展问题一：created mounted 在当前的场景下 写到这俩个里面毫无差别
 mounted优势: dom可用 echarts图表渲染  百度地图渲染
 服务端渲染: 没有mounted钩子函数 不可用
 拓展问题二：为什么要单独封装一个fetchDepartment
 1. 解构清晰 生命周期钩子函数都不应该包含太多的逻辑代码 初始化的调用代码
 2. 方便复用 在这个函数里面封装好更新列表的所有逻辑[参数二次处理 数据获取到赋值 二次处理响应]
 */
import { getDepartments, addDepartment, getDepartmentInfo, editDepartment, delDepartment, getEmployeeSimple } from '@/api/departments'

import transTree from '@/utils/transTree'
export default {
  name: 'Department',
  data() {
    const checkCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('部门编码不能为空'))
      } else {
        // 所有部门编码数组
        let codeList = this.departmentList.map(item => item.code)
        // 编辑部门时，需要去掉当前部门的code
        if (this.departInfo.id) {
          codeList = this.departmentList.filter(item => item.id !== this.departInfo.id).map(item => item.code)
        }

        // 新增部门
        if (codeList.includes(value)) {
          return callback(new Error('当前编码已存在，请重新输入'))
        } else {
          return callback()
        }
      }
    }
    return {
      treeList: [{
        name: '财务部',
        children: [
          {
            name: '财务核算部'
          },
          {
            name: '税务核算部'
          }
        ]
      }],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      addVisible: false,
      departInfo: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: checkCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },
      managerList: [],
      cutId: '',
      dialogTitle: '新增部门',
      departmentList: []
    }
  },
  mounted() {
    this.fetchDepartment()
  },
  methods: {
    // 获取部门列表
    async fetchDepartment() {
      const res = await getDepartments()
      this.departmentList = res.depts
      // 把后端返回的平铺数组转化成页面需要的树形数组
      this.treeList = transTree(res.depts)
      // console.log(this.treeList)
    },
    // 获取员工列表
    async fetchEmployeeSimple() {
      const res = await getEmployeeSimple()
      // console.log(res)
      this.managerList = res
    },
    // 获取部门详情
    async fetchDepartmentInfo(id) {
      const res = await getDepartmentInfo(id)
      // console.log(res)
      if (res.name) {
        this.departInfo = res
      }
    },
    // 打开添加部门弹框
    openAddDialog(id) {
      this.addVisible = true
      this.dialogTitle = '新增部门'
      console.log(this.managerList)
      if (this.managerList.length === 0) {
        this.fetchEmployeeSimple()
      }
      this.cutId = id
    },
    // 关闭添加部门弹框
    closeAddDialog() {
      // 关闭弹框
      this.addVisible = false
      // 清空表单
      // 清除校验痕迹
      this.$refs.addform.resetFields()
      this.departInfo = {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      }
    },
    // 提交添加部门信息
    clickSubmit() {
      this.$refs.addform.validate(async valid => {
        if (valid) {
          // 兜底验证通过
          if (this.dialogTitle === '编辑部门') {
            await editDepartment({ ...this.departInfo })
          } else {
            await addDepartment({ ...this.departInfo, pid: this.cutId })
          }
          // console.log(res)
          this.$message.success(this.dialogTitle + '成功')
          this.closeAddDialog()
          this.fetchDepartment()
        }
      })
    },
    // 打开编辑部门
    editDepart(id) {
      this.dialogTitle = '编辑部门'
      this.cutId = id
      this.fetchDepartmentInfo(id)
      this.addVisible = true
      console.log(this.managerList)
      if (this.managerList.length === 0) {
        this.fetchEmployeeSimple()
      }
    },
    delDepart(id) {
      this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
        type: 'warning',
        callback: async action => {
          if (action === 'confirm') {
            const res = await delDepartment(id)
            console.log(res)
            this.$message.success('删除成功!')
            this.fetchDepartment()
          }
        }
      })
    }
  }

}
</script>

<style lang='scss' scoped>
.el-tabs {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;

  .el-card{
    border: none;
    .el-tree{
      margin-top: 10px;
      .manager{
        text-align: right;
        padding-right: 10px;
      }
    }
  }

}
</style>
